package com.fulizhe.catlocal.integration.struts2;

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.jdbc.ScriptRunner;
import org.apache.struts2.dispatcher.Dispatcher;
import org.apache.struts2.dispatcher.DispatcherListener;

import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationException;
import com.opensymphony.xwork2.config.ConfigurationProvider;
import com.opensymphony.xwork2.inject.ContainerBuilder;
import com.opensymphony.xwork2.util.location.LocatableProperties;

public class AppLifecycleListener implements ConfigurationProvider, DispatcherListener, ServletContextListener {

	@Override
	public void destroy() {

	}

	@Override
	public void init(Configuration configuration) throws ConfigurationException {

	}

	@Override
	public boolean needsReload() {
		return false;
	}

	@Override
	public void register(ContainerBuilder builder, LocatableProperties props) throws ConfigurationException {
	}

	@Override
	public void loadPackages() throws ConfigurationException {

	}

	@Override
	public void dispatcherInitialized(Dispatcher du) {

	}

	@Override
	public void dispatcherDestroyed(Dispatcher du) {

	}

	@Override
	public void contextInitialized(ServletContextEvent sce) {
		// 初始化 h2 数据库
		try (Connection connection = MyBatisUtil.getSqlSessionFactoryUsingXML().getConfiguration().getEnvironment()
				.getDataSource().getConnection()) {
			ScriptRunner scriptRunner = new ScriptRunner(connection);
			scriptRunner.runScript(Resources.getResourceAsReader("schema/schema.sql"));
			scriptRunner.runScript(Resources.getResourceAsReader("schema/data.sql"));
		} catch (SQLException | IOException e) {
			throw new RuntimeException(e);
		}
	}

}